/**
 * Created by leiqr on 2015/6/8.
 * 运营中心首页
 */

define(function (require, exports, module) {
    var $ = require("jquery");
    var template = require("template");
    var device = require('js/detectDevice').deviceInfo;
    require('jquerycookie');
    require('js/topNotice');
    require('jqueryAppear');
    require('jqueryPagination');
    require('jquerySuperslide');
    require('js/toTop');
    //require('jqueryBizQQ');
    //var weixinShare = require('/plugins/weixin/weixinshare');

    var dialogModule = require('js/goToLogin');
    var api_prefix= api_domain +"/api/index.php?r=cms/"; //api前缀
    var jsopName = "jsonp_data";
    var guide_tips_cookie_name = 'guide_tips';//cookie 记录
    var showGuideTips = !$.cookie(guide_tips_cookie_name) && !device.os.phone && !device.os.tablet;

    
    var main = {
        init: function () {
            var self = this;
            
            this.limit = 10;
            //$.BizQQ([{selector: 'js_BizQQWPA'},{selector: 'BizQQWPABC'}]);
            var dirId = this.getQueryParams('dirId');
            this.dirId = dirId;
            this.searchArticles(dirId,1,10)
                .then(function(res){
                    if(!res){
                        dialogModule.dialog.showModal();
                        return;
                    }
                    self.renderArticleList(res.data);
                    self.createPaging(res.count);
                })
            this.bindEvt();
        },
        getQueryParams: function (para) {
            var reg = new RegExp("(^|&)" + para + "=([^&]*)(&|$)");
            var r = window.location.search.substr(1).match(reg);
            if (r != null) {
                return decodeURIComponent(r[2]);
            }
            return null;
        },
        bindEvt: function () {
            var self = this;
            $('#navbar').click(function(e){
                var target = $(e.target);
                
                var aid = target.data('aid') || target.parent().data('aid');
                if (aid !== undefined) {
                    if (aid != self.dirId){
                        $(this).find('a.nav_on').removeClass('nav_on');                     
                    }
                    var pid = target.data('pid') || target.parent().data('pid');
                    if (pid != 0) {
                        $('li[data-aid=' + pid + ']').find('a').addClass('nav_on');  
                    }
                    self.searchArticles(aid,1,10)
                        .then(function(res){
                            if(!res){
                                dialogModule.dialog.showModal();
                                return;
                            }
                            self.renderArticleList(res.data);
                            self.createPaging(res.count);
                        })
                }
            });
        },
        dateFormat: function (date, format) {
            var reg = /\d+/g;
            if (reg.test(date)) {
                date = ( date - 0) * 1000;
            }
            date = new Date(date);
            var map = {
                "M": date.getMonth() + 1, //月份
                "d": date.getDate(), //日
                "h": date.getHours(), //小时
                "m": date.getMinutes(), //分
                "s": date.getSeconds(), //秒
                "q": Math.floor((date.getMonth() + 3) / 3), //季度
                "S": date.getMilliseconds() //毫秒
            };
            format = format.replace(/([yMdhmsqS])+/g, function (all, t) {
                var v = map[t];
                if (v !== undefined) {
                    if (all.length > 1) {
                        v = '0' + v;
                        v = v.substr(v.length - 2);
                    }
                    return v;
                }
                else if (t === 'y') {
                    return (date.getFullYear() + '').substr(4 - all.length);
                }
                return all;
            });
            return format;
        },
        formatStringLen: function (str, len) {
            var strlen = 12;
            if (typeof len == 'number') {
                strlen = len;
            }
            if (typeof  str == 'string') {
                if (str.length > strlen) {
                    return str.substring(0, strlen) + '...';
                } else {
                    return str;
                }
            }
            return '';
        },
        renderArticleList: function(articles){
            template.config('escape', false);//是否编码输出 HTML 字符
            for (var i = 0; i < articles.length; i++) {
                articles[i].content = articles[i].content.replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&amp;nbsp;/g,' ');
                articles[i].content = articles[i].content.replace(/<[^>]+>/g, "");
                articles[i].title = articles[i].title.replace(/&lt;/g, '<').replace(/&gt;/g, '>');
                articles[i].title = articles[i].title.replace(/<[^>]+>/g, "");
                if (articles[i].content.length > 140) {
                    articles[i].content = articles[i].content.substring(0, 140) + '...';
                }
                articles[i].created_time_str = this.dateFormat(articles[i].modified_time,"yyyy年MM月dd日")
                // if (articles[i].title.length > 14) {
                //     articles[i].title = articles[i].title.substring(0, 14) + '...';
                // }

            }
            var html = template('articles', {articles:articles});
            $("#articleList").html(html);
        },
        searchArticles: function(dirId,page,limit){
            this.offset = page;
            this.dirId = dirId;
            page = page - 1;
            limit = limit || this.limit;
            var defer = $.Deferred();
            var url = api_prefix + "cms-search/get-article-by-dir-id&dirId=" + dirId + "&offset=" + (page * limit) + "&limit=" + limit + "&jsonp=" + jsopName;
            $.getScript(url, function () {
                defer.resolve(window[jsopName])
            })
            return defer.promise();

        },
        createPaging: function (len) {
            var self = this;
            $("#pagination").pagination(len, {
                num_edge_entries: 1, //边缘页数
                num_display_entries: 4, //主体页数
                callback: function (index) {
                    self.curpage = index - 1;
                    self.searchArticles(self.dirId,index)
                        .then(function(res){
                        if(!res){
                            dialogModule.dialog.showModal();
                            return;
                        }
                        self.renderArticleList(res.data);
                    })
                },
                items_per_page: self.pageCount, //每页显示1项
                prev_text: "前一页",
                next_text: "后一页"
            });

        }
    };

	$(function(){
		main.init();
	});
    
});







